package com.sanmao.spring.demo.security.springsecurityoauth2demo.authentication.mobile;

import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.data.redis.core.RedisTemplate;
import org.springframework.security.authentication.AuthenticationManager;
import org.springframework.security.config.annotation.SecurityConfigurerAdapter;
import org.springframework.security.config.annotation.web.builders.HttpSecurity;
import org.springframework.security.config.annotation.web.configuration.WebSecurityConfigurerAdapter;
import org.springframework.security.core.userdetails.UserDetailsService;
import org.springframework.security.web.DefaultSecurityFilterChain;
import org.springframework.security.web.authentication.AuthenticationFailureHandler;
import org.springframework.security.web.authentication.AuthenticationSuccessHandler;
import org.springframework.security.web.authentication.UsernamePasswordAuthenticationFilter;
import org.springframework.stereotype.Component;

/**
 * 手机认证配置
 * @Author: Sanmao
 * @Date: 2021/08/31/10:34
 * @Description:
 */
@Component
public class MobileAuthenticationSecurityConfig extends SecurityConfigurerAdapter<DefaultSecurityFilterChain, HttpSecurity> {

  @Autowired
  private AuthenticationSuccessHandler dmAuthenticationSuccessHandler;

  @Autowired
  private AuthenticationFailureHandler dmAuthenticationFailureHandler;

  @Autowired
  private UserDetailsService userDetailsService;

  @Autowired
  private RedisTemplate<Object, Object> redisTemplate;


  @Override
  public void configure(HttpSecurity http) throws Exception {
    MobileAuthenticationFilter mobileauthenticationfilter = new MobileAuthenticationFilter();
    mobileauthenticationfilter.setAuthenticationManager(http.getSharedObject(AuthenticationManager.class));
    mobileauthenticationfilter.setAuthenticationSuccessHandler(dmAuthenticationSuccessHandler);
    mobileauthenticationfilter.setAuthenticationFailureHandler(dmAuthenticationFailureHandler);

    MobileAuthenticationProvider MobileDaoAuthenticationProvider = new MobileAuthenticationProvider(redisTemplate, userDetailsService);
    http.authenticationProvider(MobileDaoAuthenticationProvider)
      .addFilterAfter(mobileauthenticationfilter, UsernamePasswordAuthenticationFilter.class);
  }

}
